// utils/performanceOptimizer.js
// 性能优化工具

/**
 * 性能监控器
 */
class PerformanceMonitor {
  static metrics = new Map()
  static isEnabled = true

  /**
   * 开始性能测量
   */
  static startMeasure(name) {
    if (!this.isEnabled) return

    this.metrics.set(name, {
      startTime: Date.now(),
      name
    })
  }

  /**
   * 结束性能测量
   */
  static endMeasure(name) {
    if (!this.isEnabled) return

    const metric = this.metrics.get(name)
    if (!metric) return

    const endTime = Date.now()
    const duration = endTime - metric.startTime

    metric.endTime = endTime
    metric.duration = duration

    console.log(`⏱️ [性能] ${name}: ${duration}ms`)

    // 保存性能数据
    this.saveMetric(metric)

    return duration
  }

  /**
   * 保存性能指标
   */
  static saveMetric(metric) {
    try {
      const performanceData = wx.getStorageSync('performance_data') || []
      performanceData.push({
        ...metric,
        timestamp: Date.now()
      })

      // 只保留最近100条记录
      if (performanceData.length > 100) {
        performanceData.splice(0, performanceData.length - 100)
      }

      wx.setStorageSync('performance_data', performanceData)
    } catch (error) {
      console.error('保存性能数据失败:', error)
    }
  }

  /**
   * 获取性能报告
   */
  static getPerformanceReport() {
    try {
      const performanceData = wx.getStorageSync('performance_data') || []
      
      if (performanceData.length === 0) {
        return {
          success: true,
          data: {
            totalMeasures: 0,
            averageDuration: 0,
            slowestOperations: [],
            recentPerformance: []
          }
        }
      }

      // 分析性能数据
      const groupedData = {}
      performanceData.forEach(metric => {
        if (!groupedData[metric.name]) {
          groupedData[metric.name] = []
        }
        groupedData[metric.name].push(metric.duration)
      })

      const summary = Object.keys(groupedData).map(name => {
        const durations = groupedData[name]
        const average = durations.reduce((sum, d) => sum + d, 0) / durations.length
        const max = Math.max(...durations)
        const min = Math.min(...durations)

        return {
          name,
          count: durations.length,
          average: Math.round(average),
          max,
          min
        }
      }).sort((a, b) => b.average - a.average)

      return {
        success: true,
        data: {
          totalMeasures: performanceData.length,
          averageDuration: Math.round(performanceData.reduce((sum, m) => sum + m.duration, 0) / performanceData.length),
          slowestOperations: summary.slice(0, 5),
          recentPerformance: performanceData.slice(-10)
        }
      }
    } catch (error) {
      console.error('获取性能报告失败:', error)
      return {
        success: false,
        message: '获取性能报告失败'
      }
    }
  }

  /**
   * 清除性能数据
   */
  static clearPerformanceData() {
    try {
      wx.removeStorageSync('performance_data')
      this.metrics.clear()
      return true
    } catch (error) {
      console.error('清除性能数据失败:', error)
      return false
    }
  }
}

/**
 * 防抖函数
 */
function debounce(func, wait, immediate = false) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      timeout = null
      if (!immediate) func.apply(this, args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(this, args)
  }
}

/**
 * 节流函数
 */
function throttle(func, limit) {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 内存优化器
 */
class MemoryOptimizer {
  /**
   * 清理未使用的数据
   */
  static cleanup() {
    // 清理全局变量
    if (typeof global !== 'undefined') {
      for (const key in global) {
        if (key.startsWith('temp_') || key.startsWith('cache_')) {
          delete global[key]
        }
      }
    }

    // 强制垃圾回收（如果支持）
    if (typeof wx.triggerGC === 'function') {
      wx.triggerGC()
    }
  }

  /**
   * 获取内存使用情况
   */
  static getMemoryUsage() {
    return new Promise((resolve) => {
      wx.getPerformance().getEntries().forEach(entry => {
        if (entry.entryType === 'memory') {
          resolve({
            success: true,
            data: {
              usedJSHeapSize: entry.usedJSHeapSize,
              totalJSHeapSize: entry.totalJSHeapSize,
              jsHeapSizeLimit: entry.jsHeapSizeLimit,
              usage: (entry.usedJSHeapSize / entry.totalJSHeapSize) * 100
            }
          })
          return
        }
      })
      
      // 如果没有内存信息，返回默认值
      resolve({
        success: false,
        message: '无法获取内存使用情况'
      })
    })
  }
}

/**
 * 数据缓存管理器
 */
class CacheManager {
  static cache = new Map()
  static maxSize = 50
  static ttl = 5 * 60 * 1000 // 5分钟

  /**
   * 设置缓存
   */
  static set(key, value, customTtl = null) {
    const ttl = customTtl || this.ttl
    const item = {
      value,
      timestamp: Date.now(),
      ttl
    }

    // 如果缓存已满，删除最旧的项
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value
      this.cache.delete(firstKey)
    }

    this.cache.set(key, item)
  }

  /**
   * 获取缓存
   */
  static get(key) {
    const item = this.cache.get(key)
    if (!item) return null

    // 检查是否过期
    if (Date.now() - item.timestamp > item.ttl) {
      this.cache.delete(key)
      return null
    }

    return item.value
  }

  /**
   * 删除缓存
   */
  static delete(key) {
    return this.cache.delete(key)
  }

  /**
   * 清空缓存
   */
  static clear() {
    this.cache.clear()
  }

  /**
   * 清理过期缓存
   */
  static cleanExpired() {
    const now = Date.now()
    for (const [key, item] of this.cache.entries()) {
      if (now - item.timestamp > item.ttl) {
        this.cache.delete(key)
      }
    }
  }

  /**
   * 获取缓存统计
   */
  static getStats() {
    const now = Date.now()
    let validCount = 0
    let expiredCount = 0

    for (const [key, item] of this.cache.entries()) {
      if (now - item.timestamp > item.ttl) {
        expiredCount++
      } else {
        validCount++
      }
    }

    return {
      total: this.cache.size,
      valid: validCount,
      expired: expiredCount,
      maxSize: this.maxSize
    }
  }
}

/**
 * 图片优化器
 */
class ImageOptimizer {
  /**
   * 压缩图片
   */
  static compressImage(filePath, options = {}) {
    const {
      quality = 80,
      width = null,
      height = null
    } = options

    return new Promise((resolve, reject) => {
      wx.compressImage({
        src: filePath,
        quality,
        ...(width && { width }),
        ...(height && { height }),
        success: resolve,
        fail: reject
      })
    })
  }

  /**
   * 获取图片信息
   */
  static getImageInfo(src) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src,
        success: resolve,
        fail: reject
      })
    })
  }
}

/**
 * 代码分割和懒加载
 */
class LazyLoader {
  static loadedModules = new Set()

  /**
   * 懒加载模块
   */
  static async loadModule(modulePath) {
    if (this.loadedModules.has(modulePath)) {
      return true
    }

    try {
      await import(modulePath)
      this.loadedModules.add(modulePath)
      return true
    } catch (error) {
      console.error(`懒加载模块失败: ${modulePath}`, error)
      return false
    }
  }

  /**
   * 预加载模块
   */
  static preloadModules(modulePaths) {
    modulePaths.forEach(path => {
      setTimeout(() => {
        this.loadModule(path)
      }, 100)
    })
  }
}

/**
 * 批处理优化器
 */
class BatchProcessor {
  static queues = new Map()

  /**
   * 添加到批处理队列
   */
  static add(queueName, item, processor, delay = 100) {
    if (!this.queues.has(queueName)) {
      this.queues.set(queueName, {
        items: [],
        processor,
        timer: null
      })
    }

    const queue = this.queues.get(queueName)
    queue.items.push(item)

    // 清除之前的定时器
    if (queue.timer) {
      clearTimeout(queue.timer)
    }

    // 设置新的定时器
    queue.timer = setTimeout(() => {
      this.processQueue(queueName)
    }, delay)
  }

  /**
   * 处理队列
   */
  static async processQueue(queueName) {
    const queue = this.queues.get(queueName)
    if (!queue || queue.items.length === 0) return

    const items = [...queue.items]
    queue.items = []
    queue.timer = null

    try {
      await queue.processor(items)
    } catch (error) {
      console.error(`批处理失败: ${queueName}`, error)
    }
  }

  /**
   * 立即处理队列
   */
  static async flushQueue(queueName) {
    const queue = this.queues.get(queueName)
    if (!queue) return

    if (queue.timer) {
      clearTimeout(queue.timer)
    }

    await this.processQueue(queueName)
  }
}

/**
 * 性能优化工具集合
 */
class PerformanceOptimizer {
  /**
   * 初始化性能优化
   */
  static init() {
    // 定期清理过期缓存
    setInterval(() => {
      CacheManager.cleanExpired()
      MemoryOptimizer.cleanup()
    }, 5 * 60 * 1000) // 5分钟

    console.log('🚀 性能优化器已初始化')
  }

  /**
   * 获取性能建议
   */
  static async getPerformanceAdvice() {
    const advice = []

    // 检查缓存使用情况
    const cacheStats = CacheManager.getStats()
    if (cacheStats.expired > cacheStats.valid) {
      advice.push({
        type: 'cache',
        level: 'warning',
        message: '缓存过期项过多',
        suggestion: '考虑调整缓存策略'
      })
    }

    // 检查性能数据
    const performanceReport = PerformanceMonitor.getPerformanceReport()
    if (performanceReport.success) {
      const { slowestOperations } = performanceReport.data
      if (slowestOperations.length > 0 && slowestOperations[0].average > 1000) {
        advice.push({
          type: 'performance',
          level: 'warning',
          message: `最慢操作: ${slowestOperations[0].name}`,
          suggestion: '考虑优化该操作的性能'
        })
      }
    }

    // 检查内存使用
    const memoryUsage = await MemoryOptimizer.getMemoryUsage()
    if (memoryUsage.success && memoryUsage.data.usage > 80) {
      advice.push({
        type: 'memory',
        level: 'error',
        message: '内存使用率过高',
        suggestion: '建议清理内存或优化代码'
      })
    }

    return advice
  }

  /**
   * 应用性能优化
   */
  static async applyOptimizations() {
    const results = []

    // 清理过期缓存
    CacheManager.cleanExpired()
    results.push('清理了过期缓存')

    // 内存清理
    MemoryOptimizer.cleanup()
    results.push('执行了内存清理')

    // 处理所有批处理队列
    for (const queueName of BatchProcessor.queues.keys()) {
      await BatchProcessor.flushQueue(queueName)
    }
    results.push('处理了所有批处理队列')

    return results
  }
}

export {
  PerformanceMonitor,
  PerformanceOptimizer,
  MemoryOptimizer,
  CacheManager,
  ImageOptimizer,
  LazyLoader,
  BatchProcessor,
  debounce,
  throttle
} 